package br.com.management.mentor.model.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import br.com.management.mentor.model.entities.auth.QPermission;
import br.com.management.mentor.model.entities.auth.QUser;
import br.com.management.mentor.model.entities.auth.User;

import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.Projections;

@Component
@Repository
public class UsersRepository {

	private QUser qUser = QUser.user;
	
	private QPermission qPermission = QPermission.permission;

	@Autowired
	private EntityManagerFactory emf;

	public User getByUsername( String username ) {
		EntityManager em = emf.createEntityManager();
		try {
			JPAQuery query = new JPAQuery( em );
			return query.from( qUser ).where( qUser.username.eq( username ) ).uniqueResult( qUser );
		} finally {
			if ( em != null ) em.close();
		}
	}
	
	public List<User> getActives( int firstResult, int maxResults ) {
		EntityManager em = emf.createEntityManager();
		try {
			JPAQuery query = new JPAQuery( em );
			return query.from( qUser ).where( qUser.enabled.isTrue() )
			.orderBy( qUser.username.asc() )
			.offset( firstResult ).limit( maxResults )
			.list( Projections.bean( User.class , qUser.username , qUser.creationDate , qUser.id ) );
		} finally {
			if ( em != null ) em.close();
		}
	}
	
	public List<User> getActivesByUsername( String username , int firstResult, int maxResults ) {
		EntityManager em = emf.createEntityManager();
		try {
			JPAQuery query = new JPAQuery( em );
			return query.from( qUser ).where( 
				qUser.username.lower().contains( username.toLowerCase() )
				.and( qUser.enabled.isTrue() )
			).orderBy( qUser.username.asc() )
			.offset( firstResult ).limit( maxResults )
			.list( Projections.bean( User.class , qUser.username , qUser.creationDate , qUser.id ) );
		} finally {
			if ( em != null ) em.close();
		}
	}

	public boolean thereIsAdmin() {
		EntityManager em = emf.createEntityManager();
		JPAQuery query = new JPAQuery( em );
		try {
			return query.from( qUser ).innerJoin( qUser.permissions , qPermission ).where( qUser.enabled.eq( true ).and( qPermission.name.eq( "ROLE_ADMIN" ) ) ).count() > 0l; 
		} finally {
			if ( em != null ) em.close();
		}
	}

}